package com.example.mq.mqserver;

import com.example.mq.common.*;
import com.example.mq.mqserver.core.BasicProperties;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 服务器实现
 */

@Slf4j
public class BrokerServer {
    private ServerSocket serverSocket = null;

    //创建虚拟主机
    private VirtualHost virtualHost = new VirtualHost("default");
    //哈希表存储当前所有的会话
    private ConcurrentHashMap<String, Socket> sessions = new ConcurrentHashMap<>();
    //创建一个线程池 处理多个客户端的请求
    private ExecutorService executorService = null;
    //服务器是否继续运行
    private volatile boolean runnable = true;

    public BrokerServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("[BrokeServer] 启动！");
        executorService = Executors.newCachedThreadPool();
        try {
            while (runnable) {
                //服务器接受客户端发来的请求
                Socket clientSocket = serverSocket.accept();
                //给线程池处理
                executorService.submit(() -> {
                    processConnection(clientSocket);
                });
            }
        } catch (SocketException e) {
            System.out.println("[BrokeServer] 服务器停止运行!");

        }
    }

    public void stop() throws IOException {
        //将runnable设置为false
        runnable = false;
        //关闭线程池
        executorService.shutdownNow();
        //服务器关闭
        serverSocket.close();
    }

    /**
     * 处理客户端链接 涉及多个请求和响应
     *
     * @param clientSocket
     */
    private void processConnection(Socket clientSocket) {
        try (InputStream inputStream = clientSocket.getInputStream();
             OutputStream outputStream = clientSocket.getOutputStream()) {
            try (DataInputStream dataInputStream = new DataInputStream(inputStream);
                 DataOutputStream dataOutputStream = new DataOutputStream(outputStream)) {
                while (true) {
                    //读取请求
                    Request request = readRequest(dataInputStream);
                    //计算响应
                    Response response = process(request, clientSocket);
                    //返回给客户端
                    writeResponse(dataOutputStream, response);

                }

            } catch (EOFException | SocketException | ClassNotFoundException | MqException e) {
                System.out.println("[BrokerServer] connection 关闭! 客户端的地址: " + clientSocket.getInetAddress().toString()
                        + ":" + clientSocket.getPort());
            }
        } catch (IOException e) {
            System.out.println("[BrokerServer] connection 出现异常!");
            e.printStackTrace();
        } finally {
            try {
                //关闭服务器
                clientSocket.close();
                //清理会话
                clearClosedSession(clientSocket);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 读取请求
     *
     * @param dataInputStream 输入的数据流
     * @return
     */
    private Request readRequest(DataInputStream dataInputStream) throws IOException {
        //新建一个request用于接受传来的信息
        Request request = new Request();
        //根据dataInputStream的数据为request属性赋值
        request.setType(dataInputStream.readInt());//读四个字节 存储的是类型
        request.setLength(dataInputStream.readInt()); //长度
        byte[] payload = new byte[request.getLength()];
        int n = dataInputStream.read(payload);
        if (n != request.getLength()) {
            throw new IOException("[BrokeServer] 读取请求错误");
        }
        request.setPayload(payload);
        return request;
    }

    /**
     * 写响应的数据
     *
     * @param dataOutputStream 输出的数据流
     * @param response
     * @throws IOException
     */
    private void writeResponse(DataOutputStream dataOutputStream, Response response) throws IOException {
        dataOutputStream.writeInt(response.getType());
        dataOutputStream.writeInt(response.getLength());
        dataOutputStream.write(response.getPayload());
        //刷新缓冲区 保证数据更新
        dataOutputStream.flush();
    }


    /**
     * 服务器执行主流程
     *
     * @param request      需求
     * @param clientSocket 客户端
     * @return 响应
     * @throws IOException
     * @throws ClassNotFoundException
     * @throws MqException
     */
    private Response process(Request request, Socket clientSocket) throws IOException, ClassNotFoundException, MqException {
        // 1. 把 request 中的 payload 做一个初步的解析.
        BasicArguments basicArguments = (BasicArguments) BinaryTool.fromBytes(request.getPayload());
        System.out.println("[BrockServer] request=" + request.toString());
        System.out.println("[Request] rid=" + basicArguments.getRid() + ", channelId=" + basicArguments.getChannelId()
                + ", type=" + request.getType() + ", length=" + request.getLength());
        // 2. 根据 type 的值, 来进一步区分接下来这次请求要干啥.
        boolean ok = true;
        if (request.getType() == 0x1) {
            //创建channel
            sessions.put(basicArguments.getChannelId(), clientSocket);
            System.out.println("[BrokeServer] 创建channel成功! channleId=" + basicArguments.getChannelId());
        } else if (request.getType() == 0x2) {
            //销毁channel
            sessions.remove(basicArguments.getChannelId());
            System.out.println("[BrokeServer] 删除channel 成功 channleId=" + basicArguments.getChannelId());
        } else if (request.getType() == 0x3) {
            //创建交换机
            //将参数设置为ExchangeDeclareArguments
            ExchangeDeclareArguments arguments = (ExchangeDeclareArguments) basicArguments;
            ok = virtualHost.exchangeDeclare(arguments.getExchangeName(), arguments.getExchangeType(),
                    arguments.isDurable(), arguments.isAutoDelete(), arguments.getArguments());
        } else if (request.getType() == 0x4) {
            //销毁交换机
            //修改参数类型
            ExchangeDeleteArguments arguments = (ExchangeDeleteArguments) basicArguments;
            ok = virtualHost.exchangeDelete(arguments.getExchangeName());
        } else if (request.getType() == 0x5) {
            //创建queue
            QueueDeclareArguments arguments = (QueueDeclareArguments) basicArguments;
            ok = virtualHost.queueDeclare(arguments.getQueueName(), arguments.isDurable(), arguments.isExclusive(),
                    arguments.isAutoDelete(), arguments.getArguments());
        } else if (request.getType() == 0x6) {
            //销毁queue
            QueueDeleteArguments arguments = (QueueDeleteArguments) basicArguments;
            ok = virtualHost.queueDelete((arguments.getQueueName()));
        } else if (request.getType() == 0x7) {
            //创建binding
            QueueBindArguments arguments = (QueueBindArguments) basicArguments;
            ok = virtualHost.queueBind(arguments.getExchangeName(), arguments.getQueueName(), arguments.getBindingKey());
        } else if (request.getType() == 0x8) {
            //销毁binding
            QueueUnbindArguments arguments = (QueueUnbindArguments) basicArguments;
            ok = virtualHost.queueUnbind(arguments.getQueueName(), arguments.getExchangeName());

        } else if (request.getType() == 0x9) {
            //创建message
            BasicPublishArguments arguments = (BasicPublishArguments) basicArguments;
            ok = virtualHost.basicPublish(arguments.getExchangeName(), arguments.getRoutingKey(),
                    arguments.getBasicProperties(), arguments.getBody());

        } else if (request.getType() == 0xa) {
            //销毁message
            BasicConsumeArguments arguments = (BasicConsumeArguments) basicArguments;
            ok = virtualHost.basicConsume(arguments.getConsumerTag(), arguments.getQueueName(), arguments.isAutoAck(),
                    new Consumer() {
                        @Override
                        //将服务器收到的消息直接推送回消费者客户端
                        public void handleDelivery(String consumerTag, BasicProperties basicProperties, byte[] body)
                                throws IOException, MqException {
                            //找到socket对象
                            Socket socket = sessions.get(consumerTag);
                            //判断 对象是否存在
                            if (socket == null || socket.isClosed()) {
                                throw new MqException("[BrokeServer] 订阅消息的客户端已关闭 ");
                            }

                            //构造响应数据
                            SubScribeReturns subScribeReturns = new SubScribeReturns();
                            subScribeReturns.setRid("");
                            subScribeReturns.setOk(true);
                            subScribeReturns.setChannelId(consumerTag);
                            subScribeReturns.setBasicProperties(basicProperties);
                            subScribeReturns.setBody(body);
                            subScribeReturns.setConsumerTag(consumerTag);
                            byte[] payload = BinaryTool.toBytes(subScribeReturns);

                            Response response = new Response();
                            response.setPayload(payload);
                            response.setLength(payload.length);
                            response.setType(0xc);
                            //写回客户端
                            DataOutputStream dataOutputStream = new DataOutputStream(clientSocket.getOutputStream());
                            writeResponse(dataOutputStream, response);
                        }
                    });
        } else if (request.getType() == 0xb) {
            //返回ack
            BasicAckArguments arguments = (BasicAckArguments) basicArguments;
            ok = virtualHost.basicAck(arguments.getQueueName(), arguments.getMessageId());

        } else {
            throw new MqException("[BrokeServer] 类型不存在");
        }
        //构造响应
        BasicReturns basicReturns = new BasicReturns();
        basicReturns.setRid(basicArguments.getRid());
        basicReturns.setOk(ok);
        basicReturns.setChannelId(basicArguments.getChannelId());
        byte[] payload = BinaryTool.toBytes(basicReturns);

        Response response = new Response();

        response.setType(request.getType());
        response.setLength(payload.length);
        response.setPayload(payload);
        return response;
    }


    /**
     * 删除关闭的socket键值对
     *
     * @param clientSocket
     */
    private void clearClosedSession(Socket clientSocket) {
        // 遍历sessions hash表,删除已关闭的socket对应的键值对
        List<String> toDeleteChannelId = new ArrayList<>();
        for (Map.Entry<String, Socket> entry : sessions.entrySet()) {
            if (entry.getValue() == clientSocket) {
                // 不可以在这里进行删除 边遍历遍删除不可取
                toDeleteChannelId.add(entry.getKey());
            }
        }
        for (String channelId : toDeleteChannelId) {
            sessions.remove(channelId);
        }
        System.out.println("[BrokerServer] 清理 session 完成! 被清理的 channelId=" + toDeleteChannelId);
    }


}
